#include "jCooperativeTable.h"

jCooperativeTable::jCooperativeTable()
{

}

void jCooperativeTable::Init(float travelTime, NavGraph* graph)
{
	pCTimer->Instance();
	m_timer = new PrecisionTimer();
	m_timer->Start();

	
	m_Tabletimer = new PrecisionTimer();
	m_Tabletimer->Start();

	m_TimeDistance = 5;
		
		//determined by the time it takes an agent to go from node to node.
	m_UpdateInterval = travelTime;


	for(int i = 0; i < m_TimeDistance; i++)
	{
		NavGraph* copyGraph = graph;
		NavGraph* copy_car1 = new NavGraph(*copyGraph);

		//m_SlicedSparseGraph.insert(std::pair<int,NavGraph*>(i,copy_car1));
		m_SlicedSparseGraph.push_back(copy_car1);

		copyGraph = NULL;
		delete copyGraph;
	}
}

jCooperativeTable::~jCooperativeTable()
{
m_timer = NULL;
delete m_timer;

		 if (!m_SlicedSparseGraph.empty())
		 {
			 m_SlicedSparseGraph.clear();
	     }
//delete m_SlicedSparseGraph;
}

void jCooperativeTable::MaintainTimeSlice()
{
//Get the current position in Time, delete all sparse graphs before this time
//Create copy of last sparse graph and add to container.
	int currentTime = m_Tabletimer->CurrentTime();

	//BROKEN COMPLETELY - NEEDS FIXNG
	NavGraph* navGraph = m_SlicedSparseGraph.front();
	NavGraph* navGraphCopy = new  NavGraph(*navGraph);

	m_SlicedSparseGraph.pop_front();
	m_SlicedSparseGraph.push_back(navGraphCopy);
//	m_SlicedSparseGraph.insert(std::pair<int,NavGraph*>(m_TimeDistance-1,navGraphCopy));
	
	navGraphCopy = NULL;
	delete navGraphCopy;

}

void jCooperativeTable::Update()
{
	//Every 0.3333 of a secound we want to update the table.
	double currentTime = m_timer->CurrentTime();

	//If the updateinterval time is present or has passed update the table and restart timer.
	if(currentTime >= m_UpdateInterval)
	{
		MaintainTimeSlice();
		m_timer = NULL;
		m_timer = new PrecisionTimer();
		m_timer->Start();
	}

}